<template>
	<view>
		<cu-custom class="navBox" bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">文档预览</block>
		</cu-custom>

		<u-button type="primary" :text="item.name" customStyle="width:98%;margin-top:50rpx;font-size:20rpx"
			@click="openDocument(item.url)" v-for="(item,index) in data" :key="index"></u-button>

		<u-gap height="80"></u-gap>

		<view class="" style="width: 80%;margin:0 auto" v-if="show">
			<u-line-progress :percentage="prepress" activeColor="#19be6b" height="15"></u-line-progress>
			<u-gap height="20"></u-gap>
			<u-button type="primary" text="取消下载" customStyle="width:140rpx" @click="cancelDown"></u-button>
		</view>
	</view>
</template>

<script>
	import cuCustom from '../component/colorui/components/cu-custom.vue'
	export default {
		components: {
			cuCustom
		},
		data() {
			return {
				Custom: this.Custom,
				prepress: 0,
				show: false,
				downloadTask: '',
				data: [{
					name: 'https://linbo.vip:8888/红宝书(4版)电子档.pdf (13M)',
					url: 'https://linbo.vip:8888/红宝书(4版)电子档.pdf'
				}, {
					name: 'https://linbo.vip:8888/你不知道的JavaScript上卷.pdf (34M)',
					url: 'https://linbo.vip:8888/你不知道的JAVASCRIPT 上卷.pdf'
				}, {
					name: 'https://linbo.vip:8888/你不知道的JavaScript中卷.pdf (55M)',
					url: 'https://linbo.vip:8888/你不知道的JAVASCRIPT 中卷.pdf'
				}, {
					name: 'https://linbo.vip:8888/你不知道的JavaScript下卷.pdf (31M)',
					url: 'https://linbo.vip:8888/你不知道的JAVASCRIPT 下卷.pdf'
				}, {
					name: 'https://linbo.vip:8888/深入浅出Node.js.pdf (11M)',
					url: 'https://linbo.vip:8888/深入浅出Node.js.pdf'
				}, {
					name: 'https://linbo.vip:8888/图解HTTP彩色版.pdf (13M)',
					url: 'https://linbo.vip:8888/图解HTTP+彩色版.pdf'
				}, ]
			};
		},
		methods: {
			// 打开文档预览
			openDocument(url) {
				const _this = this
				uni.showLoading({
					title: '下载中...'
				})
				this.prepress = 0
				this.show = true
				this.downloadTask = uni.downloadFile({
					url: url,
					success: function(res) {
						console.log(res)
						uni.hideLoading()
						_this.show = false

						var filePath = res.tempFilePath;
						const downloadTask = uni.openDocument({
							filePath: filePath,
							success: function(result) {
								uni.showModal({
									showCancel: false,
									'content': '文件保存至:' + res.tempFilePath
								})
								console.log('打开文档成功');
							}
						});

					}
				})
				this.downloadTask.onProgressUpdate((res) => {
					_this.prepress = res.progress
					// console.log('已经下载的数据长度' + res.totalBytesWritten);
					// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
				});
			},
			// 取消下载
			cancelDown() {
				uni.hideLoading()
				this.show = false
				this.downloadTask.abort();
				uni.showToast({
					icon: 'success',
					title: '取消成功'
				})
			}
		},
	}
</script>

<style lang="scss">

</style>
